//
//  WBStatusListDAL.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/30.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import Foundation

/// DAL - Data Access Layer 数据访问层
// 负责处理数据库和网络数据，给listViewModel返回微博的字典数组
class WBStatusListDAL {
    
    let a = AZSQLiteManager.shared
    
    /// 从本地数据库或者网络加载数据
    ///
    /// - parameter userId:     用户id
    /// - parameter since_id:   下拉刷新id
    /// - parameter max_id:     上拉刷新id
    /// - parameter completion: 完成的回调(微博的字典数组，是否成功)
    class func loadStatus(since_id: Int64, max_id: Int64, completion: @escaping ([[String:Any]]?, Bool)->()) {
        
        guard let userId = WBNetworkManager.shared.userAccount.uid else {return}
        
        // 1.检查本地数据，如果有直接返回
        let array = AZSQLiteManager.shared.loadStatus(userId: userId, since_id: since_id, max_id: max_id)
        // 2.本地没有，加载网络数据
        if array.count > 0 {
            completion(array, true)
            
            return
        }
        
        WBNetworkManager.shared.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            if !isSuccess {
                completion(nil, false)
                
                return
            }
            
            guard let list = list else {
                completion(nil, isSuccess)
                
                return
            }
            
            // 3.加载完成之后，将网络数据写入数据库
            AZSQLiteManager.shared.updateStatus(userId: userId, array: list)
            
            // 4.返回网络数据
            completion(list, isSuccess)
        }
    }
}
